# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 用户模型
包含学员、教练、校区管理员、超级管理员的统一用户模型
"""

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin

from app import db


class User(UserMixin, db.Model):
    """
    用户模型 - 统一用户表
    支持多种角色：super_admin, campus_admin, coach, student
    """
    __tablename__ = 'users'

    # 基础字段
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password_hash = db.Column(db.String(255), nullable=False, comment='密码哈希')
    real_name = db.Column(db.String(50), nullable=False, comment='真实姓名')
    role = db.Column(db.Enum('super_admin', 'campus_admin', 'coach', 'student'),
                     nullable=False, comment='用户角色')

    # 联系信息
    phone = db.Column(db.String(20), nullable=False, comment='手机号')
    email = db.Column(db.String(100), nullable=True, comment='邮箱')

    # 个人信息
    gender = db.Column(db.Enum('male', 'female'), nullable=True, comment='性别')
    age = db.Column(db.Integer, nullable=True, comment='年龄')
    photo_url = db.Column(db.String(255), nullable=True, comment='头像URL')

    # 教练专属字段
    coach_level = db.Column(db.Enum('senior', 'middle', 'junior'),
                           nullable=True, comment='教练级别')
    hourly_rate = db.Column(db.Numeric(8, 2), nullable=True, comment='每小时费用（元）')
    bio = db.Column(db.Text, nullable=True, comment='个人简介')
    experience = db.Column(db.Text, nullable=True, comment='教学经验')

    # 状态和关联
    campus_id = db.Column(db.BigInteger, db.ForeignKey('campuses.id'),
                         nullable=True, comment='所属校区')
    status = db.Column(db.Enum('active', 'inactive', 'pending'),
                      nullable=False, default='active', comment='状态')

    # 审计字段
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')

    # 关联关系
    campus = db.relationship('Campus', backref='users', lazy=True)
    student_relations = db.relationship('StudentCoachRelation',
                                       foreign_keys='StudentCoachRelation.student_id',
                                       backref='student', lazy='dynamic')
    coach_relations = db.relationship('StudentCoachRelation',
                                     foreign_keys='StudentCoachRelation.coach_id',
                                     backref='coach', lazy='dynamic')
    account = db.relationship('UserAccount', backref='user', uselist=False, lazy=True)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        # 根据角色设置默认值
        if self.role == 'student' and not self.status:
            self.status = 'active'
        elif self.role == 'coach' and not self.status:
            self.status = 'pending'

    def set_password(self, password):
        """设置密码（明文存储）"""
        self.password_hash = password

    def check_password(self, password):
        """验证密码（明文比较）"""
        return self.password_hash == password

    def is_super_admin(self):
        """是否为超级管理员"""
        return self.role == 'super_admin'

    def is_campus_admin(self):
        """是否为校区管理员"""
        return self.role == 'campus_admin'

    def is_coach(self):
        """是否为教练"""
        return self.role == 'coach'

    def is_student(self):
        """是否为学员"""
        return self.role == 'student'

    def can_manage_campus(self, campus_id):
        """是否可以管理指定校区"""
        if self.is_super_admin():
            return True
        if self.is_campus_admin() and self.campus_id == campus_id:
            return True
        return False

    def get_hourly_rate_cents(self):
        """获取小时费用（分为单位）"""
        if self.hourly_rate:
            return int(self.hourly_rate * 100)
        return 0

    def get_coach_students_count(self):
        """获取教练指导的学员数量"""
        if not self.is_coach():
            return 0
        return self.coach_relations.filter_by(status='approved').count()

    def get_student_coaches_count(self):
        """获取学员选择的教练数量"""
        if not self.is_student():
            return 0
        return self.student_relations.filter_by(status='approved').count()

    def can_add_coach(self):
        """学员是否还能添加教练"""
        if not self.is_student():
            return False
        from app.config import Config
        return self.get_student_coaches_count() < Config.MAX_COACHES_PER_STUDENT

    def can_add_student(self):
        """教练是否还能添加学员"""
        if not self.is_coach():
            return False
        from app.config import Config
        return self.get_coach_students_count() < Config.MAX_STUDENTS_PER_COACH

    @property
    def name(self):
        """获取用户姓名（real_name的别名）"""
        return self.real_name

    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'username': self.username,
            'real_name': self.real_name,
            'role': self.role,
            'phone': self.phone,
            'email': self.email,
            'gender': self.gender,
            'age': self.age,
            'photo_url': self.photo_url,
            'campus_id': self.campus_id,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'coach_level': self.coach_level,
            'hourly_rate': float(self.hourly_rate) if self.hourly_rate else None,
            'bio': self.bio,
            'experience': self.experience
        }

    def __repr__(self):
        return f'<User {self.username}: {self.real_name} ({self.role})>'